class AccountsController < ApplicationController

  # GET /accounts
  # GET /accounts.xml
  def index
    @active_section = Section.find_by_short_name("Usuarios")
    @accounts = Account.all
  end

  # GET /accounts/1
  # GET /accounts/1.xml
  def show
    @active_section = Section.find_by_short_name("Usuarios")
    @account = Account.find(params[:id])
  end

  # GET /accounts/new
  # GET /accounts/new.xml
  def new
    @active_section = Section.find_by_short_name("Usuarios")
    @account = Account.new
    @account_sections = Section.all
  end

  # GET /accounts/1/edit
  def edit
    @active_section = Section.find_by_short_name("Usuarios")
    @account = Account.find(params[:id])
    @account_sections = Section.all
  end

  # POST /accounts
  # POST /accounts.xml
  def create
    if params[:account][:category_ids]
      params[:account][:category_ids] = params[:account][:category_ids].map{|k, v| k}
    else
      params[:account][:category_ids] = []
    end    
    
    @account = Account.new(params[:account])

    respond_to do |format|
      if @account.save
        format.html { redirect_to(accounts_path, :notice => 'El usuario se creo exitosamente.') }        
      else
        format.html { render :action => "new" }       
      end
    end
  end

  # PUT /accounts/1
  # PUT /accounts/1.xml
  def update
    if params[:account][:category_ids]
      params[:account][:category_ids] = params[:account][:category_ids].map{|k, v| k}
    else
      params[:account][:category_ids] = []
    end
    
    @account = Account.find(params[:id])

    respond_to do |format|
      if @account.update_attributes(params[:account])
        format.html { redirect_to(accounts_path, :notice => 'El usuario se actualizo exitosamente.') }       
      else
        format.html { render :action => "edit" }
      end
    end
  end

  # DELETE /accounts/1
  # DELETE /accounts/1.xml
  def destroy
    @account = Account.find(params[:id])
    @account.destroy

    respond_to do |format|
      format.html { redirect_to(accounts_url) }
      format.xml  { head :ok }
    end
  end
  
  def login
    unless session[:account_id].nil?
      flash[:warn] = "Ya se encuentra logueado"
      redirect_to frente_path and return
    end

    if request.post?
      account = Account.authenticate params[:email], params[:password]
      if account and account.status != false
        session[:account_id] = account.id
        logger.info "Account #{params[:username]} connected"
        redirect_to calendar_path and return
      else
        logger.warn "Account #{params[:usuario]} failed to login"
        flash.now[:error] = "No se pudo loguear, intente de nuevo"
      end
    end
    render :layout => "login"
  end

  def logout
    session[:account_id] = nil
    logger.info "Account #{current_account.name} disconected"
    redirect_to login_url
  end
  
  
end
